package cn.itcast.order.service.impl;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.feign.client.UserClient;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.order.OrderReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.hmall.pojo.order.OrderLogistics;
import cn.itcast.hmall.pojo.user.Address;
import cn.itcast.hmall.pojo.user.User;
import cn.itcast.hmall.utils.ThreadLocalUtil;
import cn.itcast.order.mapper.OrderDetailMapper;
import cn.itcast.order.mapper.OrderLogisticsMapper;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Map;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;


    /**
     * 创建订单
     * @param orderReqDTO
     * @return
     */
    @Override
    public String addOrder(OrderReqDTO orderReqDTO) {
        //Feign远程调用商品微服务，根据id查询商品
        Item item = itemClient.queryItemById(orderReqDTO.getItemId());

        //基于商品价格、购买数量计算商品总价
        Long totalFee =orderReqDTO.getNum()*item.getPrice();
        //封装Order对象，初始status为  未支付
        Order order = new Order();
        Long userId = ThreadLocalUtil.getUserId();
        order.setTotalFee(totalFee); //金额
        order.setPaymentType(orderReqDTO.getPaymentType()); //支付方式
        order.setUserId(userId);//用户id
        order.setStatus(1); // 支付状态 未支付

        //将order添加到数据库表中
        orderMapper.insert(order);
        // 将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(item.getId());
        orderDetail.setNum(orderReqDTO.getNum());
        orderDetail.setName(item.getName());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());

        orderDetailMapper.insert(orderDetail);

        //Feign远程调用user微服务，根据id查询地址
        Address address = userClient.queryAddressById(orderReqDTO.getAddressId());

        //将地址封装为OrderLogistics对象，写入tb_order_logistics表(物流信息表)
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(orderDetail.getOrderId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setMobile(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setTown(address.getTown());
        orderLogistics.setStreet(address.getStreet());
        orderLogisticsMapper.insert(orderLogistics);

        //Feign远程调用 修改商品库存
        if (item.getStock()>=orderReqDTO.getNum()){
            item.setStock(item.getStock()-orderReqDTO.getNum());
        }

        //有库存
        if (item.getStock()>0){
            itemClient.updateItem(item);
        }

        return order.getId().toString();
    }


    /**
     *订单支付
     * @param
     * @return
     */
    @Override
    public ResultDTO payOrder(Long orderId, Map<String,String> key) {
        //Feign 根据id查询用户信息
        //获取当前登录用户id
        Long userId = ThreadLocalUtil.getUserId();
        User user = userClient.findUserById(userId);

        Order order = orderMapper.selectById(orderId);
        if (order.getStatus()==1){
            //获取密码
            String password = key.get("password");
            if (user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
                //密码正确 扣除消费金额
                user.setBalance(user.getBalance()-order.getTotalFee());
                //修改用户
                userClient.updateUserById(user);

                //把订单状态改为已支付
                order.setStatus(2);
                orderMapper.updateById(order);
                return ResultDTO.ok();
        }
        }
        return ResultDTO.error();
    }
}
